from django.http import JsonResponse
from django.utils.deprecation import MiddlewareMixin
from django.core.cache import cache

# 豁免token验证的地址
except_paths = ['/api/userinfo/log', '/api/iotutils', '/favicon.ico', '/admin']


# 验证用户token的中间件
class AuthMiddleWare(MiddlewareMixin):
    def process_request(self, request):
        flag = False
        for except_path in except_paths:
            if request.path.startswith(except_path):
                flag = True
        if flag:
            pass
        else:
            header = request.META
            tokenStr = header['HTTP_AUTHORIZATION']
            userId = cache.get(tokenStr)
            if userId:
                request.userId = userId
            else:
                res = {
                    'status': 404,
                    'message': "登录信息已经过期，请重新登录"
                }
                return JsonResponse(res)



